package com.znf4.base;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.util.ByteArrayBuffer;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.znf4.constants.CommonConst;
import com.znf4.trade.exception.TradeBizException;
import com.znf4.user.info.entity.UserInfo;
import com.znf4.utils.StringUtil;


/**
 * 支付网关Controller基础类
 */
public abstract class BaseController {

	protected final Log log = LogFactory.getLog(this.getClass());

	private static final String UTF_8 = "utf-8";
	protected static final String RESPONSE_CODE = "code";
	protected static final String RESPONSE_MESSAGE = "msg";
	protected static final String RESPONSE_ERROR = "error";

	

	/**
	 * 获取request
	 * 
	 * @return
	 */
	protected HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	/**
	 * 获取session
	 * 
	 * @return
	 */
	protected HttpSession getSession() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
	}

	/**
	 * 取当前登录的用户
	 * 
	 * @return
	 */
	protected UserInfo getCurrentUser(HttpServletRequest request) {
		return (UserInfo) request.getSession().getAttribute(CommonConst.BOOS);
	}

	/**
	 * 设置当前登录的用户到session
	 * 
	 * @param userInfo
	 */
	protected void updateCurrentUser(UserInfo userInfo, HttpServletRequest request) {
		request.getSession().setAttribute(CommonConst.BOOS, userInfo);
	}

	/**
	 * 获取application
	 * 
	 * @return
	 */
	protected ServletContext getApplication() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession().getServletContext();
	}

	protected ServletContext getServletContext() {
		return ContextLoader.getCurrentWebApplicationContext().getServletContext();
	}

	public String getString(String name) {
		return getString(name, null);
	}

	public String getString(String name, String defaultValue) {
		String resultStr = getRequest().getParameter(name);
		if (resultStr == null || "".equals(resultStr) || "null".equals(resultStr) || "undefined".equals(resultStr)) {
			return defaultValue;
		} else {
			return resultStr;
		}
	}
	
	public String getReuquestHeadToString(){
		//Header部分
		HttpServletRequest request = getRequest();
	    System.out.print(request.getHeaderNames());
	    log.info("getHeaderNames:"+request.getHeaderNames());
	    Enumeration<?> enum1 = request.getHeaderNames();
	    while (enum1.hasMoreElements()) {
	        String key = (String) enum1.nextElement();
	        String value = request.getHeader(key);
	        System.out.println(key + "\t" + value);
	        log.info(key + "\t" + value);
	    }
	    return "";
	}
	
	
	public String getRequestInputStreamToString() {
		String param = null;
		try {
			HttpServletRequest res = getRequest();
			ServletInputStream in = res.getInputStream();
			param = readStringFromInputStream(in);
		} catch (IOException e) {
			log.error("get fast pay inputsteam exception :", e);
		}
		return param;
	}

	private String readStringFromInputStream(InputStream is) throws IOException {
		byte[] buf = new byte[4096];
		int len = 0;
		ByteArrayBuffer bytes = new ByteArrayBuffer(4096);

		while (true) {
			len = is.read(buf);
			if (len >= 0) {
				bytes.append(buf, 0, len);
			} else {
				break;
			}
		}
		return new String(bytes.toByteArray(), "UTF-8");
	}

	/**
	 * 获取请求中的参数值，如果参数值为null刚转为空字符串""
	 * 
	 * @return
	 */
	public Map<String, Object> getParamMap_NullStr(Map map) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		Set keys = map.keySet();
		for (Object key : keys) {
			String value = this.getString(key.toString());
			if (value == null) {
				value = "";
			}
			parameters.put(key.toString(), value);
		}
		return parameters;
	}

	/**
	 * 将请求参数封装成一个Map
	 * 
	 * @return
	 */
	public Map<String, Object> getParameterMap() {

		// 参数Map
		Map properties = getRequest().getParameterMap();
		// 返回值Map
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Iterator entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if (null == valueObj) {
				value = "";
			} else if (valueObj instanceof String[]) {
				String[] values = (String[]) valueObj;
				for (int i = 0; i < values.length; i++) {
					value = values[i] + ",";
				}
				value = value.substring(0, value.length() - 1);
			} else {
				value = valueObj.toString();
			}
			returnMap.put(name, value);
		}
		return returnMap;
	}

	/**
	 * 将请求参数封装成一个Map_中文使用gbk格式转换
	 * 
	 * @return
	 */
	public Map<String, Object> getParameterMap_GBK() {

		// 参数Map
		Map properties = getRequest().getParameterMap();
		// 返回值Map
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Iterator entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if (null == valueObj) {
				value = "";
			} else if (valueObj instanceof String[]) {
				String[] values = (String[]) valueObj;
				for (int i = 0; i < values.length; i++) {
					value = values[i] + ",";
				}
				value = value.substring(0, value.length() - 1);
				try {
					byte[] fullByte = new String(value.getBytes("ISO-8859-1"), "UTF-8").getBytes("GBK");
					value = new String(fullByte, "GBK");
				} catch (UnsupportedEncodingException e) {
				}

			} else {
				value = valueObj.toString();
				try {
					byte[] fullByte = new String(value.getBytes("ISO-8859-1"), "UTF-8").getBytes("GBK");
					value = new String(fullByte, "GBK");
				} catch (UnsupportedEncodingException e) {
				}
			}
			returnMap.put(name, value);
		}
		return returnMap;
	}

	/**
	 * 将请求参数封装成一个Map_中文使用gbk格式转换
	 *
	 * @return
	 */
	public Map<String, Object> getGBKParameterMap() {

		HttpServletRequest httpServletRequest = getRequest();
		try {
			httpServletRequest.setCharacterEncoding("GBK");
		} catch (UnsupportedEncodingException e) {
			return null;
		}

		// 参数Map
		Map properties = httpServletRequest.getParameterMap();
		// 返回值Map
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Iterator entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if (null == valueObj) {
				value = "";
			} else if (valueObj instanceof String[]) {
				String[] values = (String[]) valueObj;
				for (int i = 0; i < values.length; i++) {
					value = values[i] + ",";
				}
				value = value.substring(0, value.length() - 1);
				try {
					byte[] fullByte = value.getBytes("GBK");
					value = new String(fullByte, "GBK");
				} catch (UnsupportedEncodingException e) {
				}

			} else {
				value = valueObj.toString();
				try {
					byte[] fullByte = value.getBytes("GBK");
					value = new String(fullByte, "GBK");
				} catch (UnsupportedEncodingException e) {
				}
			}
			returnMap.put(name, value);
		}
		return returnMap;
	}

	public int getInt(String name) {
		return getInt(name, 0);
	}

	public int getInt(String name, int defaultValue) {
		String resultStr = getRequest().getParameter(name);
		if (resultStr != null) {
			try {
				return Integer.parseInt(resultStr);
			} catch (Exception e) {
				log.error("参数转换错误:", e);
				return defaultValue;
			}
		}
		return defaultValue;
	}

	public BigDecimal getBigDecimal(String name) {
		return getBigDecimal(name, null);
	}

	public BigDecimal getBigDecimal(String name, BigDecimal defaultValue) {
		String resultStr = getRequest().getParameter(name);
		if (resultStr != null) {
			try {
				return BigDecimal.valueOf(Double.parseDouble(resultStr));
			} catch (Exception e) {
				log.error("参数转换错误:", e);
				return defaultValue;
			}
		}
		return defaultValue;
	}

	/**
	 * 根据参数名从HttpRequest中获取String类型的参数值，无值则返回"" .
	 * 
	 * @param key
	 *            .
	 * @return String .
	 */
	public String getString_UrlDecode_UTF8(String key) {
		try {
			String string = getString(key.toString());
			if (StringUtil.isEmpty(string)) {
				return null;
			} else {
				return URLDecoder.decode(this.getString(key), UTF_8);
			}
		} catch (Exception e) {
			log.error("URL解码错误:", e);
			return "";
		}

	}

	public String getString_UrlDecode_GBK(String key) {
		try {
			String string = getString(key.toString());
			if (StringUtil.isEmpty(string)) {
				return null;
			} else {
				return new String(getString(string).getBytes("GBK"), "UTF-8");
			}
		} catch (Exception e) {
			log.error("参数转码错误:", e);
			return "";
		}

	}

	/**
	 * 获取客户端的IP地址
	 * 
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) {
		String ipAddress = null;
		ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					log.error("未知主机", e);
				}
				ipAddress = inet.getHostAddress();
			}

		}

		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) {
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	/**
	 * 获取refererUrl
	 */
	public String getRefererUrl(HttpServletRequest request) {
		return request.getHeader("referer");
	}

	public String readRequest(HttpServletRequest request) throws IOException {
		StringBuilder sb = new StringBuilder();
		try {
			String line;
			while ((line = request.getReader().readLine()) != null) {
				sb.append(line);
			}
		} finally {
			request.getReader().close();
		}
		return sb.toString();
	}

	public void write(HttpServletResponse response, String s) {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(s);
		} catch (IOException e) {
			log.error("返回支付结果接收状态到微信支付错误", e);
		} finally {
			out.close();
		}
	}

	protected byte[] generateSuccessJson(Map<String, Object> successInfo) throws Exception {
		JSONObject resultObj = new JSONObject();
		resultObj.put(RESPONSE_CODE, 200);
		Set<String> keySet = successInfo.keySet();
		for (String key : keySet) {
			resultObj.put(key, successInfo.get(key));
		}
		return resultObj.toJSONString().getBytes("UTF-8");
	}

	protected byte[] generateFailureJson(Map<String, Object> failureInfo) throws Exception {
		JSONObject resultObj = new JSONObject();
		resultObj.put(RESPONSE_CODE, 300);
		Set<String> keySet = failureInfo.keySet();
		for (String key : keySet) {
			resultObj.put(key, failureInfo.get(key));
		}
		return resultObj.toJSONString().getBytes("UTF-8");
	}

}
